const MusicPage = require("./MusicPage");
const fs = require("fs");
const Config = require("./Config");
const Download = require("./Download");
const path = require("path");
const {sleep} = require("./Helper");
const IgnoreSong = require('./IgnoreSong');
class Song
{
    /**
     *
     * @type {browserManager|null}
     */
    #browserManager = null;


    /**
     *
     * @type {User|null}
     */
    #user = null;
    constructor(browserManager,user)
    {
        this.#browserManager = browserManager;
        this.#user = user;
    }

    async downloadPlayListSongs()
    {
        const userInfo = await this.#user.getProfile();

        // 云盘已存在歌曲 ID 文件夹
        const cloudPath = path.resolve(Config.cloudSongIdsDir, userInfo.user_id.toString());
        if (!fs.existsSync(cloudPath))
        {
            console.log('云盘文件夹不存在，无需排除已存在歌曲');
            fs.mkdirSync(cloudPath, { recursive: true });
        }
        // 歌单保存目录
        const playListPath = Config.playListDir;
        if (!fs.existsSync(playListPath))
        {
            console.log('歌单目录不存在');
            return;
        }

        // 读取所有歌单 JSON 文件
        const playListFiles = fs.readdirSync(playListPath).filter(f => f.endsWith('.txt'));

        for (const file of playListFiles)
        {
            const filePath = path.join(playListPath, file);
            const content = fs.readFileSync(filePath, 'utf-8');

            let songList;
            try {
                songList = JSON.parse(content);
            } catch (e) {
                console.error(`解析 ${file} 失败:`, e);
                continue;
            }

            for (const item of songList)
            {
                const songId = item.id || item.songId || item.song_id;
                if (!songId) continue;

                const songFilePath = path.join(cloudPath, `${songId}.txt`);
                if (fs.existsSync(songFilePath)) {
                    // 已存在云盘里，跳过
                    console.log(`歌曲 ${songId} 已存在，跳过`);
                    continue;
                }

                // 下载歌曲
                if (item.href)
                {
                    try {
                        console.log(`开始访问歌曲: ${songId} ${item.title} `);
                        const res = await this.downloadSong(item.href);
                        if (res)  {
                            // 下载完成后在云盘目录生成标记文件
                            fs.writeFileSync(songFilePath, '1');
                            console.log(item.title+'---下载完成或下载中');
                        }

                    } catch (e) {
                        console.error(`下载 ${songId} 失败:`, e);
                    }
                }

                // 等待 2 秒，防止请求过快
                await sleep(5000);
            }
        }

        console.log('歌单下载完成,目录:'+"\n"+Config.downloadDir);


    } //end downloadPlayList

    async downSingerSongs(data = {songMap:[]})
    {
        const songMap = data.songMap;
        const userInfo = this.#user.getProfile();
        const cloudPath = path.resolve(Config.cloudSongIdsDir, userInfo.toString());
        for (const name in songMap)
        {
            console.log('到'+name);

            let list = songMap[name];
            for (const item of list)
            {
                console.log('即将下载'+name+`-《${item.album}》 ${item.songId}`);
                const songFilePath = path.join(cloudPath, `${item.songId}.txt`);
                if (fs.existsSync(songFilePath)) {
                    // 已存在云盘里，跳过
                    console.log(`歌曲 ${item.songId} 已存在，跳过`);
                    continue;
                }

                if (IgnoreSong.hasBySongId(item.songId))
                {
                    // 已存在云盘里，跳过
                    console.log(`歌曲 ${item.songId} 忽略，跳过`);
                    continue;
                }

                let url = 'https://music.163.com/song?id='+item.songId;

                try {
                    const res = await this.downloadSong(url);
                    if (res)  {
                        // 下载完成后在云盘目录生成标记文件
                        fs.writeFileSync(songFilePath, '1');
                        console.log(item.title+'---下载完成或下载中');
                    }

                } catch (e) {
                    console.error(`下载 ${songId} 失败:`, e);
                }
                await sleep(3000);

            } //end for list

        } //end for songMap

    } //end downSingerSong


    async downloadSong(url)
    {

        const page = await this.#browserManager.openPage(url, this.#user.getCookie());

        const downloadUrl = await MusicPage.getMusicDownloadUrl(page)
        await page.close();
        if (!downloadUrl) return ;
        if (!fs.existsSync(Config.downloadDir)) {
            fs.mkdirSync(Config.downloadDir);
        }
        await Download.downloadWithHeaders(downloadUrl, Config.downloadDir,url, this.#user.getCookie())

    }

}




module.exports = Song